package com.itgacl.magic4j.libcommon.component.ws;

import com.itgacl.magic4j.libcommon.component.cache.redis.RedisClient;
import com.itgacl.magic4j.libcommon.util.IpUtil;
import com.itgacl.magic4j.libcommon.util.SpringContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class WsSessionManager {

    /**
     * 保存WebSocketSession连接
     */
    public static ConcurrentHashMap<String, WebSocketSession> webSocketSessionPool = new ConcurrentHashMap<>();
    public static ConcurrentHashMap<String, String> webSocketClientPool = new ConcurrentHashMap<>();

    /**
     * 添加 WebSocketSession
     * @param clientId
     */
    public static void add(String clientId, WebSocketSession session) {
        // 添加 session
        webSocketSessionPool.put(clientId, session);
        webSocketClientPool.put(session.getId(), clientId);
        RedisClient redisService = SpringContextUtils.getBean(RedisClient.class);
        String connServerIp = IpUtil.getLocalIP();//客户端连接的服务器IP地址
        redisService.set(clientId,connServerIp);//存储客户端连接的服务器地址
        log.debug("客户端{}连接的服务器为：{}",clientId,connServerIp);
    }

    /**
     * 删除 WebSocketSession,会返回删除的 WebSocketSession
     * @param clientId
     * @return
     */
    public static WebSocketSession remove(String clientId) {
        // 删除 session
        WebSocketSession session = webSocketSessionPool.remove(clientId);
        webSocketClientPool.remove(session.getId());
        RedisClient redisService = SpringContextUtils.getBean(RedisClient.class);
        redisService.del(clientId);
        return session;
    }

    /**
     * 删除并同步关闭连接
     * @param clientId
     */
    public static void removeAndClose(String clientId) {
        WebSocketSession session = remove(clientId);
        if (session != null) {
            try {
                webSocketClientPool.remove(session.getId());
                RedisClient redisService = SpringContextUtils.getBean(RedisClient.class);
                redisService.del(clientId);
                // 关闭连接
                session.close();
            } catch (IOException e) {
                log.error(e.getMessage(),e);
            }
        }
    }

    /**
     * 获得 session
     * @param clientId
     * @return
     */
    public static WebSocketSession get(String clientId) {
        // 获得 session
        return webSocketSessionPool.get(clientId);
    }

    /**
     * 获取客户端连接的服务器IP
     * @param clientId
     * @return
     */
    public static String getConnServer(String clientId){
        RedisClient redisService = SpringContextUtils.getBean(RedisClient.class);
        return redisService.get(clientId);
    }
}